package us.wili.dev.platform.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import us.wili.dev.common.model.ResponseDto;
import us.wili.dev.common.util.ResponseUtil;
import us.wili.dev.platform.service.PlatformFileService;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/api")
@Api(tags = "七牛云接口")
public class WebServerController {
    private static final Logger logger = Logger.getLogger(WebServerController.class);

    @Resource
    private PlatformFileService platformFileService;
    /**
     * 上传图片文件七牛云
     * @param files
     * @return
     */
    @ApiOperation(value = "上传",nickname = "imgs")
    @RequestMapping(value = "/imgs",method = RequestMethod.POST)
    public ResponseDto uploadImg(@RequestParam("files")  MultipartFile[] files) throws IOException {

        // 返回类型可以自己定义
        List<String>  serviceResult = new ArrayList<>();

        // 验证非空
        if (StringUtils.isBlank(files[0].getOriginalFilename())) {
            // serviceResult = new ServiceResult().dataIsNot();
        } else {
            Map<String, List<String>> map = new HashMap<>();

            map = platformFileService.uploadImgs(files);

            List<String> resultList = map.get("result");
            logger.info("图片上传返回结果:"+resultList);

            if ("error".equals(resultList.get(0))) {
                //  serviceResult = new ServiceResult().dataIsNot();
            } else {
                //  serviceResult = new ServiceResult(resultList);
            }
            for (String s : resultList) {
                String url ="http://vrqn.liuliangin.com/"+s.replace("?","%3f");
                serviceResult.add(url);
                serviceResult.add(files[0].getOriginalFilename());
            }
        }
        return ResponseUtil.getSuccessRsp(serviceResult);
    }

    @ApiOperation(value = "token",nickname = "uptoken")
    @RequestMapping(value = "/uptoken",method = RequestMethod.POST)
    public ResponseDto uploadImg() throws IOException {
        return ResponseUtil.getSuccessRsp(platformFileService.uptoken());
    }

}
